import 'package:elevator/get/message.dart';
import 'package:elevator/model/build_info.dart';
import 'package:elevator/utils/utils_logger.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';

import '../../../../model/lift_info.dart';
import '../../../../model/user.dart';
import '../../../../utils/eventbus.dart';

class DetailNewLogic extends GetxController {

  late LiftInfo liftInfo;
  late BuildInfo  buildInfo;
  int psAuth = 0;
  late User user;

  final int ID_LIFT_INFO = 0x1002;

  PageController pageController= PageController(viewportFraction: 1.0);

  var pageIndex = 0.obs;

  String? busOnKey;

  @override
  void onInit() {
    buildInfo = Get.arguments["buildInfo"];
    liftInfo = Get.arguments["liftInfo"];
    psAuth = Get.arguments["psAuth"];
    user = Get.arguments["user"];
    debugPrint("DetailNewLogic:onInit:liftInfo_${buildInfo.buildId}_${liftInfo.order}");
    super.onInit();
  }

  @override
  void onReady() {
    debugPrint("DetailNewLogic:onReady:liftInfo_${buildInfo.buildId}_${liftInfo.order}");
    super.onReady();
  }

  void register(){
    if(null!=busOnKey){
      unregister();
    }
    busOnKey = '${bus.liftInfo_Key}${buildInfo.buildId}_${liftInfo.order}';
    debugPrint("DetailNewLogic:register:liftInfo_${buildInfo.buildId}_${liftInfo.order}");
    bus.on(busOnKey, busCallback);
  }

  void unregister(){
    debugPrint("DetailNewLogic:unregister:$busOnKey");
    if(null != busOnKey){
      bus.off(busOnKey, busCallback);
      busOnKey = null;
    }
  }

  busCallback(arg){
    if(liftInfo.order==arg.order){
      liftInfo = arg;
      update([ID_LIFT_INFO]);
    }
  }

  @override
  void onClose() {
    debugPrint("DetailNewLogic:onClose:liftInfo_${buildInfo.buildId}_${liftInfo.order}");
    super.onClose();
  }

  String getBuildName(){
    return Messages.isCzLocal? buildInfo.buildDetail.buildNameCn:buildInfo.buildDetail.buildNameEn;
  }

  void changePageByIndex(int index) {
    if (index < 0 || index >= 5 || pageIndex.value == index) return;

    pageIndex.value = index;
    pageController.animateToPage(
      index, // 切换到第二页
      duration: const Duration(milliseconds: 300),
      curve: Curves.ease,
    );
  }

  void gotoBuildDetail() {
    Get.toNamed("/build_detail",arguments: {"buildInfo":buildInfo,"user":user});
  }

  var showDatePicker = true.obs;
  int timeIndex = 0;
  var startTimeStr = '开始时间'.obs;
  var endTimeStr = '结束时间'.obs;
  var pickTime  = getTimeWithoutHms();
  var startTime = getTimeWithoutHms();
  var endTime = getTimeWithoutHms();

  static DateTime getTimeWithoutHms({DateTime? dateTime}) {
    dateTime ??= DateTime.now();
    return DateTime(dateTime.year, dateTime.month, dateTime.day);
  }

  void showDatePickDialog() {
    Get.dialog(AlertDialog(
        content:SizedBox(
          height: 400,
          width: 300,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // Text("请选择查询日期"),
              // 横向开始和结束时间
              Row(children: [
                // 日期标签
                Text("日期"),
                TextButton(onPressed: () {
                  showDatePicker.value = true;
                  if (showDatePicker.value) {
                    timeIndex = 0;
                  }
                }, child: Obx(() {
                  return Text(startTimeStr.value);
                })),
                TextButton(onPressed: () {
                  showDatePicker.value = true;
                  if (showDatePicker.value) {
                    timeIndex = 1;
                  }
                }, child: Obx(() {
                  return Text(endTimeStr.value);
                })),
              ],),
              Obx(() {
                return Visibility(
                  visible: showDatePicker.value,
                  child: Container(
                    color: Colors.grey,
                    child: Column(
                      children: [
                        SizedBox(
                          height: 200,
                          child: CupertinoDatePicker(
                            mode: CupertinoDatePickerMode.date,
                            initialDateTime: pickTime,
                            onDateTimeChanged: (DateTime value) {
                              logd('onDateTimeChanged$value');
                              pickTime = getTimeWithoutHms(dateTime: value);
                            },
                          ),
                        ),
                        ElevatedButton(onPressed: () {
                          logd('ElevatedButton $timeIndex pickTime=$pickTime endTime=$endTime');
                          if (timeIndex == 0) {
                            if (!pickTime.isAtSameMomentAs(endTime) && !pickTime.isBefore(endTime)) {
                              Get.snackbar('', 'Wrong Time');
                              return;
                            }
                            startTimeStr.value = '${pickTime.year}-${pickTime.month}-${pickTime.day}';
                            startTime = pickTime;
                          }else {
                            if (!pickTime.isAtSameMomentAs(startTime) && pickTime.isBefore(startTime)) {
                              Get.snackbar('', 'Wrong Time');
                              return;
                            }
                            endTimeStr.value = '${pickTime.year}-${pickTime.month}-${pickTime.day}';
                            endTime = pickTime;
                          }
                          showDatePicker.value = false;
                        }, child:Text('确认')),
                      ],
                    ),
                  ),
                );
              }),
              Spacer(),
              // 取消和确认按钮
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  ElevatedButton(onPressed: () {
                    Get.back();
                  }, child: Text("取消")),
                  ElevatedButton(onPressed: () {
                    bus.emit(bus.errorTimePickedKey, [startTime, endTime]);
                    Get.back();
                  }, child: Text("查询")),
                ],
              )
            ],

          ),
        )
    )).whenComplete(() {
      timeIndex = 0;
    });
  }

  void goToSettingPage() { Get.toNamed("/setting",arguments: {"user":user});}

}
